﻿using Microsoft.Maui.ApplicationModel;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EbookReader
{
    public class CommonFunctions
    {
        public static long GetTimeStampSeconds()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0);
            return (long)ts.TotalSeconds;
        }

        public static DateTime TimeStampSeconds2DateTime(long timeStamp)
        {
            //GameDebug.LogError($"TimeStampSeconds2DateTime timeStamp:{timeStamp}  GetTimeStampSeconds():{GetTimeStampSeconds()}");
            return new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(timeStamp);
        }

        /// <summary>
        /// 时间转换天时分秒显示
        /// </summary>
        /// <returns>The stamp to HM.</returns>
        /// <param name="seconds">seconds</param>
        public static string TimeToDHMS(double secondsd)
        {
            var seconds = (int)secondsd;
            var day = seconds / 86400;
            var secondsInDay = seconds % 86400;
            var hour = secondsInDay / 3600;
            var minute = (secondsInDay - hour * 3600) / 60;
            var second = secondsInDay - hour * 3600 - minute * 60;
            if (day > 0)
            {
                return string.Format("{0}d {1:D2}:{2:D2}:{3:D2}", day, hour, minute, second);
            }
            else
            {
                return string.Format("{0:D2}:{1:D2}:{2:D2}", hour, minute, second);
            }
        }
        public static void TimeToDHMS(double secondsd, out int day, out int hour, out int minute, out int second)
        {
            var seconds = (int)secondsd;
            day = seconds / 86400;
            int secondsInDay = seconds % 86400;
            hour = secondsInDay / 3600;
            minute = (secondsInDay - hour * 3600) / 60;
            second = secondsInDay - hour * 3600 - minute * 60;
        }

        public static string GetTimeElapsed(long timestamp)
        {
            int elaSec = (int)(GetTimeStampSeconds() - timestamp);

            TimeToDHMS(elaSec, out int day, out int hour, out int min, out int sec);

            if (day > 0)
            {
                return $"{day}天";
            }
            else if (hour > 0)
            {
                return $"{hour}小时";
            }
            else if (min > 0)
            {
                return $"{min}分钟";
            }
            else //if (elaSec > 0)
            {
                elaSec = elaSec / 10 * 10;
                return $"{elaSec}秒";
            }
        }

        public static string TimeToMS(double secondsd)
        {
            var seconds = (int)secondsd;
            var minute = seconds / 60;
            var second = seconds - minute * 60;
            return string.Format("{0:D2}:{1:D2}", minute, second);
        }

        public static DateTime GetTimeZoneDateTime(long timestamp)
        {
            DateTime utcDate = DateTimeOffset.FromUnixTimeSeconds(timestamp).DateTime;
            TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
            DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(utcDate, timeZone);
            return localTime;
        }
        public static DateTime GetTimeZoneNowDateTime()
        {
            TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
            DateTime utcNow = DateTime.Now.ToUniversalTime();
            DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(utcNow, timeZone);
            return localTime;
        }

        public static Bitmap ScaleTexture(Bitmap source,int maxSize)
        {
            if (source == null)
                return null;

            int width = source.Width;
            int height = source.Height;
            if (width <= maxSize && height <= maxSize)
            {
                return source;
            }
            float rate = 1;
            if (width > height)
            {
                rate = width / (float)maxSize;
            }
            else
            {
                rate = height / (float)maxSize;
            }
            var newtexture = ScaleTexture(source, (int)(width / rate), (int)(height / rate));
            return newtexture;
        }
        public static Bitmap ScaleTexture(Bitmap originalBitmap, int newWidth, int newHeight)
        {
            if (originalBitmap == null)
                return null;

            Bitmap scaledBitmap = new Bitmap(newWidth, newHeight);

            // 使用 Graphics 类进行缩放
            using (Graphics g = Graphics.FromImage(scaledBitmap))
            {
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(originalBitmap, 0, 0, newWidth, newHeight);
            }
            originalBitmap.Dispose();

            return scaledBitmap;
        }
        public static byte[] ConvertBitmapToJpegBytes(Bitmap bitmap)
        {
            if (bitmap == null)
                return null;



            using (MemoryStream memoryStream = new MemoryStream())
            {
                // Create an Encoder object based on the GUID for the Compression parameter category
                System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Compression;

                // create encode parameters
                //EncoderParameters myEncoderParameters = new EncoderParameters(1);
                //EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, (long)EncoderValue.CompressionCCITT4);
                //myEncoderParameters.Param[0] = myEncoderParameter;

                // 设置JPEG格式的保存参数，可以调整压缩质量
                EncoderParameters encoderParameters = new EncoderParameters(1);
                encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 80L); // 80% 的质量

                // 获取JPEG格式编码器
                ImageCodecInfo jpgEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);

                // 将 Bitmap 保存到 MemoryStream
                //bitmap.Save(memoryStream, jpgEncoder, myEncoderParameters);
                bitmap.Save(memoryStream, jpgEncoder, encoderParameters);

                // 获取包含JPG格式的 byte[]
                byte[] jpegBytes = memoryStream.ToArray();

                return jpegBytes;
            }
        }

        static ImageCodecInfo GetEncoder(System.Drawing.Imaging.ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }
    }
}
